/*
 * @Descripttion: 
 * @version: 
 * @Author: yuanliutech
 * @Date: 2022-11-01 14:23:34
 * @LastEditors: yuanliutech@lwj
 * @LastEditTime: 2025-03-20 14:16:32
 */
const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
const chooseLocation = requirePlugin('chooseLocation');
import {
    showMsg
} from '../../../utils/config.js'
import {
    validateEmoji,
    validateSpecial
} from '../../../utils/validate.js'
import {
    reqSpaceEdit,
    reqRegion,
    reqRegionLevel,
} from '../../../request/api'

var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min'); //地址转经纬度
// 实例化API核心类
var qqmapsdk = new QQMapWX({ //地址转经纬度
    key: '6YRBZ-CE263-TES33-YGBKX-AJ2SH-I4FJH' // 必填,申请的key
})

Page({
    data: {
        navHeight: app.globalData.navHeight + 'px', //头部距离
        bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
        parkId: '', //园区id
        form: {
            id: '',
            name: '',
            lng: '',
            lat: '',
            region: '',
            province: '',
            provinceCode: '',
            city: '',
            cityCode: '',
            area: '',
            areaCode: '',
            street: '',
            streetCode: '',
            community: '',
            communityCode: '',
            address: '',
            buildingType: '', //建筑物性质 
            buildingTypeText: '',
            isDefence: false,
        },
        provinceList: [], //省列表
        cityList: [], //市列表
        areaList: [], //区列表
        streetList: [], //街道列表
        communityList: [], //社区列表
        showprovince: false, //省弹窗
        showcity: false, //市弹窗
        showarea: false, //区弹窗
        showStreet: false, //是否展示街道弹窗
        showCommunity: false, //是否展示社区弹窗
        buildingTypeList: [{
            id: 1,
            text: "住宅",
        },
        {
            id: 2,
            text: "旅店",
        },
        {
            id: 3,
            text: "公司",
        },
        {
            id: 4,
            text: "出租屋",
        },
        {
            id: 5,
            text: "餐饮",
        },
        {
            id: 6,
            text: "商店",
        },
        {
            id: 7,
            text: "医院",
        },
        {
            id: 8,
            text: "娱乐场所",
        },
        {
            id: 9,
            text: "生产加工企业和仓库",
        },
        {
            id: 10,
            text: "爱心屋",
        },
        {
            id: 11,
            text: "充电桩",
        },
        {
            id: 99,
            text: "其他",
        }
        ],
        showBuildingType: false, //是否展示建筑物性质弹窗
        radio: "1", //单个添加/批量添加
        floorName: '', //单个添加楼层名称
        batchNameList: [{
            id: 0,
            start: '',
            end: ''
        },], //批量添加
        disabledBtn: false,
    },
    onLoad(e) {
        this.getItemInfo(e)
    },
    async onShow() {
        await this.getLocation() //获取地图地址信息
        await this.Region() //省
        await this.RegionLevel() //市
        await this.RegionLevel2() //区
    },
    // 查询省级行政单位
    async Region() {
        const res = await reqRegion()
        if (res.code !== 20000) return showMsg(res.message)
        console.log(res);
        this.setData({
            provinceList: res.data.rows
        })
    },
    async RegionLevel() {
        const res = await reqRegionLevel(this.data.form.provinceCode)
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        console.log(rows);
        this.setData({
            cityList: rows
        })
    },
    async RegionLevel2() {
        const res = await reqRegionLevel(this.data.form.cityCode)
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        console.log(rows);
        this.setData({
            areaList: rows
        })
    },
    onReady() {
        let pickerType = this.selectComponent('.picker-buildingType') //隔离因素
        pickerType.setIndexes([this.data.form.buildingType - 1])
    },
    // 获取信息
    getItemInfo(e) {
        let item = JSON.parse(e.item)
        console.log(item);
        this.setData({
            parkId: item.parkId,
            'form.orgId': item.orgId,
            'form.id': item.id,
            'form.name': item.name,
            'form.lng': item.lng,
            'form.lat': item.lat,
            'form.region': item.province + item.city + item.area,
            'form.province': item.province,
            'form.provinceCode': item.provinceCode,
            'form.city': item.city,
            'form.cityCode': item.cityCode,
            'form.area': item.area,
            'form.areaCode': item.areaCode,
            'form.street': item.street,
            'form.streetCode': item.streetCode,
            'form.community': item.community,
            'form.communityCode': item.communityCode,
            'form.address': item.address,
            'form.buildingType': item.buildingType,
            'form.isDefence': item.isDefence === 1 ? true : false,
        })
        if (item.areaCode) {
            this.getStreet1(item.areaCode) //获取街道列表
        }
        if (item.streetCode) {
            this.getCommunity(item.streetCode) //获取社区列表
        }
    },
    // 获取名称
    nameChange(e) {
        this.data.form.name = validateEmoji(e.detail.value.replace(/\s+/g, ''))
        this.setData({
            "form.name": this.data.form.name
        })
    },
    // 清除名称
    clearName() {
        this.setData({
            "form.name": ''
        })
    },
    //点击腾讯地图选点获取位置
    getLocationClick() {
        wx.showLoading({
            title: '加载中',
            mask: true,
        })
        // wgs84   gcj02
        wx.getLocation({
            type: 'wgs84',
            isHighAccuracy: false, //开启高精度定位
            success(res) {
                wx.hideLoading()
                const key = '44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53'; //使用在腾讯位置服务申请的key
                const referer = '精卫安'; //调用插件的app的名称
                const location = JSON.stringify({
                    latitude: res.latitude,
                    longitude: res.longitude
                });
                const category = '生活服务,娱乐休闲，公司企业';
                wx.navigateTo({
                    url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}&category=${category}`
                });
            },
            fail(err) {
                console.log(err);
                wx.showToast({
                    title: '定位失败,请在微信小程序设置中>位置信息>打开定位功能',
                    icon: 'none',
                    duration: 3000
                })
            }
        })
    },
    // 依据腾讯地图选点获取位置
    getLocation() {
        const location = chooseLocation.getLocation(); // 如果点击确认选点按钮，则返回选点结果对象，否则返回null
        if (location !== null) {
            console.log(location);
            this.setData({
                // "form.lng": location.longitude,
                // "form.lat": location.latitude,
                "form.region": location.province + location.city + location.district,
                "form.province": location.province || location.name,
                "form.city": location.city,
                "form.area": location.district,
                "form.address": location.name,
            })
            this.getProvince(location)
        }
    },

    // 获取省级编码
    async getProvince(location) {
        wx.showLoading({
            title: '加载中',
            mask: true,
        })

        const res = await reqRegion()
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        let data = ''
        rows.forEach(item => {
            if (item.regionName === this.data.form.province) {
                data = item
            }
        })
        this.setData({
            'form.provinceCode': data.regionCode
        })
        this.getCity(location, data.regionCode)
    },
    // 获取市级编码
    async getCity(location, code) {
        const res = await reqRegionLevel(code)
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        this.setData({
            cityList: rows
        })
        let data = ''
        console.log(rows, location);
        rows.forEach(item => {
            if (item.regionName === location.city) {
                data = item
            }
        })
        // 市辖区查不到  默认选择第一个  
        if (data == "") {
            this.setData({
                'form.city': rows[0].regionName,
                'form.cityCode': rows[0].regionCode,
                // 'form.street': ""
            })
            // wx.hideLoading()
            // return;
        } else {
            this.setData({
                'form.cityCode': data.regionCode
            })
        }
        this.getArea(location, data.regionCode || rows[0].regionCode)
    },
    // 获取区级编码
    async getArea(location, code) {
        const res = await reqRegionLevel(code)
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        let data = ''
        this.setData({
            areaList: rows
        })
        rows.forEach(item => {
            if (item.regionName === location.district) {
                data = item
            }
        })
        // 市辖区查不到  清空  
        if (data == "") {
            this.setData({
                'form.area': "",
                'form.street': ""
            })
            wx.hideLoading()
            return;
        }
        this.setData({
            'form.areaCode': data.regionCode
        })
        this.getStreet(data.regionCode)
    },
    // 获取街道
    async getStreet(code) {
        const res = await reqRegionLevel(code)
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        console.log(rows);
        this.setData({
            streetList: rows,
            'form.street': "",
            'form.community': "",
            showStreet: true
        })
        await this.geocoder(this.data.form.province + this.data.form.city + this.data.form.area + this.data.form.street)
        wx.hideLoading()
    },
    // 不改变地区直接改变街道
    async getStreet1(code) {
        const res = await reqRegionLevel(code)
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        this.setData({
            streetList: rows,
        })
        wx.hideLoading()
    },
    // 获取社区
    async getCommunity(code) {
        const res = await reqRegionLevel(code)
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        this.setData({
            communityList: rows,
        })
        wx.hideLoading()
    },
    // 弹出省
    showprovinceClick() {
        this.setData({
            showprovince: true
        })
    },
    // 关闭省弹窗
    provinceClose() {
        this.setData({
            showprovince: false
        })
    },
    // 弹出市
    showcityClick() {
        this.setData({
            showcity: true
        })
    },
    // 关闭市弹窗
    cityClose() {
        this.setData({
            showcity: false
        })
    },
    // 弹出区
    showareaClick() {
        this.setData({
            showarea: true
        })
    },
    // 关闭区弹窗
    areaClose() {
        this.setData({
            showarea: false
        })
    },
    // 关闭街道弹窗
    streetClose() {
        this.setData({
            showStreet: false
        })
    },
    // 弹出街道
    showStreetClick() {
        this.setData({
            showStreet: true
        })
    },
    // 关闭社区弹窗
    communityClose() {
        this.setData({
            showCommunity: false
        })
    },
    // 弹出社区
    showCommunityClick() {
        this.setData({
            showCommunity: true
        })
    },
    // 省确认
    provinceConfirm(e) {
        console.log(e);
        let location = {
            province: e.detail.value.regionName,
        }
        this.setData({
            "form.province": e.detail.value.regionName, //省
            showprovince: false
        })
        this.getProvince(location)
    },
    // 市确认
    cityConfirm(e) {
        let location = {
            city: e.detail.value.regionName,
        }
        this.setData({
            "form.city": e.detail.value.regionName, //市
            showcity: false
        })
        this.getCity(location, this.data.form.provinceCode)
    },
    // 区确认
    areaConfirm(e) {
        let location = {
            district: e.detail.value.regionName,
        }
        this.setData({
            "form.area": e.detail.value.regionName, //区
            'form.street': "",
            showarea: false
        })
        this.getArea(location, this.data.form.cityCode)
    },
    // 街道确认
    async streetConfirm(e) {
        console.log(e);
        const {
            value,
        } = e.detail;
        this.setData({
            'form.streetCode': value.regionCode,
            'form.street': value.regionName,
            'form.communityCode': '',
            'form.community': '',
        })
        this.streetClose()
        // 获取社区列表
        const res = await reqRegionLevel(value.regionCode)
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        this.setData({
            communityList: rows,
        })
        await this.geocoder(this.data.form.province + this.data.form.city + this.data.form.area + this.data.form.street)
    },
    async communityConfirm(e) {
        console.log(e);
        const {
            value,
        } = e.detail;
        this.setData({
            'form.communityCode': value.regionCode,
            'form.community': value.regionName,
        })
        this.communityClose()
    },
    // 获取详细地址
    addressChange(e) {
        this.setData({
            "form.address": e.detail.value
        })
    },
    // 清除详细地址
    clearAddress() {
        this.setData({
            "form.address": ''
        })
    },

    // 弹出建筑物性质
    clickBuildingType() {
        this.setData({
            showBuildingType: true
        })
    },
    // 隐藏建筑物性质
    buildingTypeClose() {
        this.setData({
            showBuildingType: false
        })
    },
    // 确定建筑物性质
    buildingTypeConfirm(e) {
        const {
            value,
            index
        } = e.detail;
        this.setData({
            "form.buildingType": value.id,
            "form.buildingTypeText": value.text,
            showBuildingType: false,
        })
    },


    // 点击布撤防
    changeDefence(e) {
        let tip = e.detail ? '此操作将开启该建筑物所有设备布防设置，是否继续？' : '此操作将关闭该建筑物所有设备布防设置，是否继续？'
        Dialog.confirm({
            title: '温馨提示',
            message: tip,
        })
            .then(async () => {
                this.setData({
                    "form.isDefence": e.detail
                })
            })
            .catch(() => { });
    },

    // 地址转经纬度
    geocoder(address) {
        console.log(address);
        //调用地址解析接口
        qqmapsdk.geocoder({
            //获取表单传入地址
            address: address, //地址
            success: (res) => { //成功后的回调
                console.log(res.result.location.lng, '成功后的回调')
                console.log(res.result.location.lat, '成功后的回调')
                this.setData({
                    "form.lng": res.result.location.lng,
                    "form.lat": res.result.location.lat,
                })
            },
            fail: function (error) {
                console.error(error, 'error的回调');
            },
            complete: function (res) {
                console.log(res, 'complete的回调');
            }
        })
    },

    /**
     * @name: 确认新增建筑物
     * @msg: *orgId:组织id  *parkId：园区id *name：名称  *address:详细地址   *lng：精度  *lat：纬度  *isDefence：布撤防  *buildingType：空间类型  childrenName批量新增下级空间名称
     * @return {*}
     */

    async confirm() {
        if (this.data.disabledBtn) return
        let {
            form
        } = this.data
        if (!(form.name)) return showMsg("请输入名称")
        if (!(form.areaCode)) return showMsg("请选择地区")
        if (!(form.province)) return showMsg("请选择省")
        if (!(form.city)) return showMsg("请选择市")
        if (!(form.area)) return showMsg("请选择区")
        if (!(form.street)) return showMsg("请选择街道")
        if (!(form.address)) return showMsg("请输入详细地址")
        if (!validateSpecial(form.name)) return

        await this.geocoder(this.data.form.province + this.data.form.city + this.data.form.area + this.data.form.street)

        let params = {
            orgId: form.orgId,
            id: form.id,
            name: form.name,
            lng: form.lng,
            lat: form.lat,
            province: form.province,
            provinceCode: form.provinceCode,
            city: form.city,
            cityCode: form.cityCode,
            area: form.area,
            areaCode: form.areaCode,
            street: form.street,
            streetCode: form.streetCode,
            community: form.community,
            communityCode: form.communityCode,
            address: form.address,
            isDefence: form.isDefence ? 1 : 0,
            buildingType: form.buildingType,
            childrenName: [],
            picList: [],
            village: ''
        }
        this.reqSpaceAddFun(params)
    },

    async reqSpaceAddFun(params) {
        const res = await reqSpaceEdit(params)
        if (res.code != 20000) return showMsg(res.message)
        showMsg("编辑成功", "success")
        this.setData({
            disabledBtn: true
        })
        setTimeout(() => {
            wx.navigateBack({
                delta: 1,
            })
        }, 2000)
    },
    onUnload() {
        // 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
        chooseLocation.setLocation(null);
    },

})